package com.bowen.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bowen.common.to.mq.SeckillOrderTo;
import com.bowen.common.utils.R;
import com.bowen.common.vo.MemberRespVo;
import com.bowen.seckill.feign.CouponFeignService;
import com.bowen.seckill.feign.ProductFeignService;
import com.bowen.seckill.interceptor.LoginUserInterceptor;
import com.bowen.seckill.service.SeckillService;
import com.bowen.seckill.to.SeckillSkuRedisTo;
import com.bowen.seckill.vo.SeckillSessionsWithSkus;
import com.bowen.seckill.vo.SeckillSkuVo;
import com.bowen.seckill.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    RedissonClient redissonClient;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";

    private final String SKUKILL_CACHE_PREFIX = "seckill:skus";

    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";//+商品随机码

    @Override
    public void uploadSeckillSkuLatest3Days() {
        //1.扫描最近3天需要参与秒杀的活动
        R r = couponFeignService.getLates3DaySession();
        if (r.getCode() == 0){
            //上架商品
            List<SeckillSessionsWithSkus> data = r.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {
            });
            //缓存到redis
            //1.缓存活动信息
            saveSessionInfos(data);
            //2.缓存活动的关联商品信息
            saveSessionSkuInfos(data);
        }
    }

    //返回当前时间可以参与秒杀的商品信息
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        //1.确定当前时间属于那个秒杀场次
        long time = new Date().getTime();

        Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
        for (String key : keys) {
            String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
            String[] s = replace.split("_");
            Long start = Long.parseLong(s[0]);
            Long end = Long.parseLong(s[1]);
            if (time >= start && time<= end){
                //2.获取这个秒杀场次的所有商品信息
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                List<String> list = hashOps.multiGet(range);
                if (list !=null){
                    List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                        SeckillSkuRedisTo redisTo = JSON.parseObject(item.toString(), SeckillSkuRedisTo.class);
//                        redisTo.setRandomCode(null);
                        return redisTo;
                    }).collect(Collectors.toList());
                    return collect;
                }
                break;
            }
        }

        return null;
    }

    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        //1.找到所有需要参与秒杀的商品key
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        if (keys !=null && keys.size()>0)
        {
            String reg = "\\d_"+skuId;
            for (String key : keys) {
//                String[] s = key.split("_");
                if (Pattern.matches(reg,key)){
                    String json = hashOps.get(key);
                    SeckillSkuRedisTo seckillSkuRedisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
                    //随机码
                    long time = new Date().getTime();
                    Long startTime = seckillSkuRedisTo.getStartTime();
                    Long endTime = seckillSkuRedisTo.getEndTime();
                    if (time>=startTime && time<=endTime){
                    }else {
                        seckillSkuRedisTo.setRandomCode(null);
                    }
                    return seckillSkuRedisTo;

                }
            }
        }
        return null;
    }

    /**
     * 更多做的是流量消峰 ,TODO 上架秒杀商品的时候，每一个数据都有过期时间
     * TODO 秒杀后续的流程 ，简化了收货地址等信息。
     * @param killId 7-1
     * @param key
     * @param num
     * @return
     */
    @Override
    public String kill(String killId, String key, Integer num) {
        long s1 = System.currentTimeMillis();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        //1.获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = ops.get(killId);
        if (StringUtils.isEmpty(json)) {
            return null;
        }else {
            SeckillSkuRedisTo skuRedisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
            //校验合法性
            Long startTime = skuRedisTo.getStartTime();
            Long endTime = skuRedisTo.getEndTime();
            long time = new Date().getTime();

            long ttl = endTime - time;
            //1.校验时间的合法性
            if (time >= startTime && time <=endTime){
                //2.校验随机码和商品id
                String randomCode = skuRedisTo.getRandomCode();
                String sku = skuRedisTo.getPromotionSessionId()+"_"+ skuRedisTo.getSkuId();
                if (randomCode.equals(key) && killId.equals(sku)){
                        //3.验证购物数量是否合理
                    if (num <= skuRedisTo.getSeckillLimit().intValue()) {
                        //4.验证这人是否已经购买过。幂等性； 如果只要秒杀成功，就去占位。 userId_SessionId_sku
                        //SETNX
                        //自动过期
                        String redisKey = memberRespVo.getId()+"_"+sku;
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (aBoolean) {
                            //占位成功说明从来没有买过
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                                boolean b = semaphore.tryAcquire(num);
                                if (b){
                                    //秒杀成功
                                    //快速下单.发送MQ消息 10毫秒
                                    String replace = UUID.randomUUID().toString().replace("_", "");
                                    SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                                    seckillOrderTo.setOrderSn(replace);
                                    seckillOrderTo.setMemberId(memberRespVo.getId());
                                    seckillOrderTo.setNum(num);
                                    seckillOrderTo.setPromotionSessionId(skuRedisTo.getPromotionSessionId());
                                    seckillOrderTo.setSkuId(skuRedisTo.getSkuId());
                                    seckillOrderTo.setSeckillPrice(skuRedisTo.getSeckillPrice());
                                    rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",seckillOrderTo);
                                    long s2 = System.currentTimeMillis();
                                    log.info("耗时...",(s2-s1));
                                    return replace;
                                }
                                    return null;

                        }else {
                            //说明已经买过了
                            return null;
                        }
                    }
                }else {
                    return null;
                }

            }else {
                return null;
            }
        }

        return null;
    }


    private void saveSessionInfos(List<SeckillSessionsWithSkus> sessions){
        if(sessions != null && sessions.size() >0){
            sessions.stream().forEach(sessions1 ->{
                long startTime = sessions1.getStartTime().getTime();
                long endTime = sessions1.getEndTime().getTime();
                String key = SESSIONS_CACHE_PREFIX+startTime+"_"+endTime;
                Boolean hasKey = redisTemplate.hasKey(key);
                //缓存活动信息
                if (!hasKey){
                    List<String> collect = sessions1.getRelationSkus().stream().map(item -> item.getPromotionSessionId().toString()+"_"+ item.getSkuId().toString()).collect(Collectors.toList());
                    redisTemplate.opsForList().leftPushAll(key, collect);
                }
            });
        }
    }

    private void saveSessionSkuInfos(List<SeckillSessionsWithSkus> sessions){
        sessions.stream().forEach(sessions1 ->{
            //准备hash操作
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            sessions1.getRelationSkus().stream().forEach(seckillSkuVo -> {
                //4.随机码？ 安全
                String token = UUID.randomUUID().toString().replace("-", "");
                if (!ops.hasKey(seckillSkuVo.getPromotionSessionId().toString()+"_"+seckillSkuVo.getSkuId().toString())) {
                    //缓存商品
                    SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                    //1.sku的基本数据
                    R info = productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                    if (info.getCode() == 0){
                        SkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfoVo(skuInfo);
                    }
                    //2.sku的秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo,redisTo);

                    //3.随机码，设置当前秒杀的时间信息
                    redisTo.setStartTime(sessions1.getStartTime().getTime());
                    redisTo.setEndTime(sessions1.getEndTime().getTime());

                    redisTo.setRandomCode(token);

                    String jsonString = JSON.toJSONString(redisTo);
                    ops.put(seckillSkuVo.getPromotionId().toString() +"_"+ seckillSkuVo.getSkuId().toString(),jsonString);

                    //如果当前场次的商品的库存信息已经上架就不要上架
                    //5.使用库存作为分布式的信号量  限流
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    //商品可以秒杀的数量作为信号量
                    semaphore.trySetPermits(seckillSkuVo.getSeckillCount().intValue());
                }


            });
        });
    }
}
